/*
	Adobe Systems Incorporated(r) Source Code License Agreement
	Copyright(c) 2007 Adobe Systems Incorporated. All rights reserved.
	
	Please read this Source Code License Agreement carefully before using
	the source code.
	
	Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, 
	no-charge, royalty-free, irrevocable copyright license, to reproduce,
	prepare derivative works of, publicly display, publicly perform, and
	distribute this source code and such derivative works in source or 
	object code form without any attribution requirements.  
	
	The name "Adobe Systems Incorporated" must not be used to endorse or promote products
	derived from the source code without prior written permission.
	
	You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and
	against any loss, damage, claims or lawsuits, including attorney's 
	fees that arise or result from your use or distribution of the source 
	code.
	
	THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT 
	ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  ALSO, THERE IS NO WARRANTY OF 
	NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT.  IN NO EVENT SHALL ADOBE
	OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
	OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
	WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
	OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF
	ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.adobe.apps.ascension
{

	import flash.media.Sound;
	import flash.net.URLRequest;
	import flash.media.SoundChannel;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import com.adobe.apps.ascension.Song;
	import flash.events.IOErrorEvent;
	import com.adobe.apps.ascension.events.MP3PlayerEvent;
	import flash.media.SoundTransform;
	
	
	[Event(name="complete", type="com.adobe.apps.ascension.events.MP3PlayerEvent")]
	[Event(name="play", type="com.adobe.apps.ascension.events.MP3PlayerEvent")]
	[Event(name="pause", type="com.adobe.apps.ascension.events.MP3PlayerEvent")]	
	
	public class MP3Player extends EventDispatcher
	{
		private var _pausePosition:Number = 0;
		private var _sound:Sound;
		private var _channel:SoundChannel;
		private var _song:Song;
		private var _playing:Boolean = false;
		
		private var _soundTransform:SoundTransform = new SoundTransform();
		
		public function play(song:Song, autoPlay:Boolean = true):void
		{
			//listen for error
			
			var newSong:Boolean = false;
			if(song != _song)
			{
				newSong = true;
				//todo: why is this here?
				if(_song != null)
				{
					_song.playing = false;
				}
				
				_clear();
				
				//new sound
				_song = song;
				
				
				_song.playing = true;
				_pausePosition = 0;
				_sound = new Sound();	
				_sound.addEventListener(IOErrorEvent.IO_ERROR, onIOError);

				_sound.load(new URLRequest(_song.path));
						
			}

			if(!autoPlay)
			{
				return;
			}

			if(playing)
			{
				restart();
			}
			else
			{
				_play(newSong);
			}
			
		}	
		
		private function onIOError(event:IOErrorEvent):void
		{
			trace("Cant Load Song : " + _song.artist + " : " + _song.title + " - " + 
														event.text);
														
			_playing = false;											
			//if we get an IOError, we dispatch a sound complete event so we 
			//can move to next song
			//eventually we will redispatch the IOErrorEvent	
			var e:MP3PlayerEvent = new MP3PlayerEvent(MP3PlayerEvent.SONGCOMPLETE);
				e.song = _song;
			dispatchEvent(e);
		}
		
		public function get playing():Boolean
		{
			return _playing;
		}
		
		private function onSoundComplete(event:Event):void
		{
			_playing = false;
			
			var e:MP3PlayerEvent = new MP3PlayerEvent(MP3PlayerEvent.SONGCOMPLETE);
				e.song = _song;
			dispatchEvent(e);
		}
		
		public function get song():Song
		{
			return _song;
		}
		
		private function _play(newSong:Boolean = false):void
		{
			//in rememberence: on this line, mike chambers made a dumb mistake
			
			_sound.addEventListener(Event.COMPLETE, onSoundLoad);
			
			_channel = _sound.play(_pausePosition);
			_channel.soundTransform = _soundTransform;
			_channel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);	
			_playing = true;
			
			//only broadcast if the song is being resumed so we don't broadcast play
			//twice on first play
			if(!newSong)
			{
				//todo: should this be a RESUME event?
				var e:MP3PlayerEvent = new MP3PlayerEvent(MP3PlayerEvent.SONGPLAY);
					e.song = _song;
			
				dispatchEvent(e);
			}
		}
		
		private function onSoundLoad(event:Event):void
		{
			var e:MP3PlayerEvent = new MP3PlayerEvent(MP3PlayerEvent.SONGPLAY);
				e.song = _song;
			
			dispatchEvent(e);
		}
		
		private function _clear():void
		{
			if(_channel != null)
			{
				//this is so complete event doesnt get broadcast twice when a new song is sent
				_channel.removeEventListener(Event.SOUND_COMPLETE, onSoundComplete);
			}
			
			if(_channel != null)
			{
				_channel.stop();
			}
			
			if(_sound != null && _sound.isBuffering)
			{
				_sound.close();
			}
			
			_playing = false;
			
		}
		
		public function pause():void
		{
			_pausePosition = _channel.position;
			_channel.stop();
			_playing = false;
			
			var e:MP3PlayerEvent = new MP3PlayerEvent(MP3PlayerEvent.SONGSTOP);
				e.song = _song;
			
			dispatchEvent(e);
		}
		
		
		public function restart():void
		{
			seek(0);
		}
		
		
		public function stop():void
		{
			_clear();
			var e:MP3PlayerEvent = new MP3PlayerEvent(MP3PlayerEvent.SONGSTOP);
				e.song = _song;
			
			dispatchEvent(e);
		}
		
		public function get position():Number
		{
			if(_channel != null)
			{
				return _channel.position;
			}
			
			return -1;
		}
		
		private function seek(position:Number):void
		{
			_pausePosition = position;
			_channel.stop();
			_play();
		}
		
		public function set position(value:Number):void
		{
			if(value > -1)
			{
				seek(value);
			}
		}
	
		public function get length():Number
		{
			if(_sound != null)
			{
				return _sound.length;
			}
			
			return -1;
		}
		
		//private var _volume:Number = 1;
		[Bindable]
		public function set volume(value:Number):void
		{
			_soundTransform.volume = value;
			
			if(_channel == null)
			{
				return;
			}
			
			_channel.soundTransform = _soundTransform;
		}
		
		public function get volume():Number
		{		
			return _soundTransform.volume;
		}
	}
}